package com.talent.talentgateway.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName：JwtCheckFilter
 * @Author: hszhou
 * @Date: 2025/2/13 16:42
 * @Description: 拦截请求获取token
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class JwtTokenCheckFilter implements GlobalFilter, Ordered {

    private final StringRedisTemplate redisTemplate;

    @Value("${whites.urls:/admin/login,/auth/oauth/token,/user/demo,/order/demo}")
    private Set<String> whiteList;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        //改接口是否需要token 才能访问
        if(!isRequireToken(exchange)){
            return chain.filter(exchange);
        }
        //获取用户的token
        String token = getHeaderToken(exchange);
        if(token==null || token.isEmpty()){
            return buildNoAuthorization(exchange);
        }
        //判读用户的token是否有效
        if (redisTemplate.hasKey(token)) {
            return chain.filter(exchange);
        }
        return buildNoAuthorization(exchange);
    }

    private Mono<Void> buildNoAuthorization(ServerWebExchange exchange) {

        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        Map<String, Object> map = new HashMap<>();
        map.put("err","请先登录");
        DataBuffer wrap = response.bufferFactory().wrap(map.toString().getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(wrap));
    }

    private String getHeaderToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token==null?null:token.replace("bearer ", "");
    }

    private boolean isRequireToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        if(whiteList.contains(path)){
            return false;
        }
        return true;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
